package cn.aloyii.demos.web;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author cutezoo
 */
@RestController
public class WxController {
    
    @GetMapping("/")
    public String check(String signature, String timestamp,
                        String nonce, String echostr) {
/*        System.out.println("signature:" + signature);
        System.out.println("timestamp:" + timestamp);
        System.out.println("nonce:" + nonce);
        System.out.println("echostr:" + echostr);*/

//        1）将token、timestamp、nonce三个参数进行字典序排序
        String token = "lovezyj";
//        2）将三个参数字符串拼接成一个字符串进行sha1加密
        List<String> list = Arrays.asList(token, timestamp, nonce);
        Collections.sort(list);
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : list) {
            stringBuilder.append(s);
        }
        MessageDigest instance = null;
        try {
            instance = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        //使用sha1进行加密，获得byte数组
        byte[] digest = instance.digest(stringBuilder.toString().getBytes());
        // 将digest转换成16进制
        //写法1：
        String hash = bytesToHex(digest);
        //写法2：
        /*StringBuilder sum =  new StringBuilder();
        for (byte b : digest) {
            sum.append(Integer.toHexString((b>>4)&15));
            sum.append(Integer.toHexString(b&15));
        }*/

//        3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if (hash.equals(signature)) {
            return echostr;
        }
        return null;
    }
    
    /**
     * 将字节数组转换为十六进制字符串
     * 原因：SHA-1 加密后得到的字节数组通常需要转换为十六进制字符串格式以便于查看和比较。
     * 这是因为字节数组可能包含不可打印的字符，而且直接输出字节数组的结果
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
    
    @GetMapping("/hello")
    public String hello() {
        return "hello wechat";
    }
    
    @PostMapping("/")
    public String receiveMessage(HttpServletRequest request){
        System.out.println("收到用户的消息");
        return "";
    }
}
